<script setup lang="ts">
import { ref, reactive, h, onMounted } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import { ElMessage, ElTag, ElButton, ElMessageBox } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import {
  getGithubTasks,
  deleteGithubTask,
  executeGithubTask,
  updateGithubTask,
} from "../../servers";
import DynamicForm from "@/components/DynamicForm";
import AddTaskDialog from "./components/AddTaskDialog.vue";
import TaskDetailDialog from "./components/TaskDetailDialog.vue";

const props = defineProps<{
  task: string;
}>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const taskList = ref<any[]>([]);
const loading = ref(false);
const formRef = ref<any>(null);
const showAddTaskDialog = ref(false);
const showEditTaskDialog = ref(false);
const currentEditTask = ref<any>(null);
const showDetailDialog = ref(false);
const currentDetailTaskId = ref<number | null>(null);

// 筛选表单数据
const filterForm = reactive({
  status: "",
  keyword: "",
});

// 筛选表单配置
const formConfig = [
  {
    key: "status",
    name: "状态",
    type: "select" as const,
    defaultValue: "",
    placeholder: "全部",
    params: {
      clearable: true,
    },
    options: [
      { label: "全部", value: "" },
      { label: "待执行", value: "pending" },
      { label: "执行中", value: "running" },
      { label: "已完成", value: "completed" },
      { label: "失败", value: "failed" },
    ],
    labelWidth: "80px",
  },
  {
    key: "keyword",
    name: "搜索",
    type: "input" as const,
    defaultValue: "",
    placeholder: "请输入关键词",
    params: {
      clearable: true,
    },
    col: {
      span: 6,
    },
  },
];

const historyColumns = ref<TableColumn[]>([
  {
    label: "任务名称",
    prop: "task_name",
    minWidth: 200,
    show: true,
  },
  {
    label: "任务编码",
    prop: "task_code",
    width: 150,
    show: true,
  },
  {
    label: "主关键词",
    prop: "main_keyword",
    width: 150,
    show: true,
  },
  {
    label: "场景类型",
    prop: "scenario_types",
    width: 200,
    show: true,
    render: (row) => {
      try {
        const scenarios = JSON.parse(row.scenario_types || "[]");
        if (Array.isArray(scenarios) && scenarios.length > 0) {
          return scenarios.join(", ");
        }
      } catch (e) {
        // 解析失败，返回原值
      }
      return row.scenario_types || "-";
    },
  },
  {
    label: "状态",
    prop: "task_status",
    width: 120,
    show: true,
    render: (row) => {
      const statusMap: Record<
        string,
        { text: string; type: "success" | "warning" | "info" | "danger" | "" }
      > = {
        pending: { text: "待执行", type: "warning" },
        running: { text: "执行中", type: "info" },
        completed: { text: "已完成", type: "success" },
        failed: { text: "失败", type: "danger" },
      };
      const item = statusMap[row.task_status] || {
        text: row.task_status,
        type: "info" as const,
      };
      return h(
        ElTag,
        { type: item.type || "info", size: "small" },
        () => item.text
      );
    },
  },
  {
    label: "调度状态",
    prop: "schedule_enabled",
    width: 100,
    show: true,
    render: (row) => {
      return h(
        ElTag,
        {
          type: row.schedule_enabled ? "success" : "info",
          size: "small",
        },
        () => (row.schedule_enabled ? "已启用" : "未启用")
      );
    },
  },
  {
    label: "执行频率",
    prop: "cron_expression",
    width: 150,
    show: true,
    render: (row) => {
      if (!row.cron_expression) return "-";
      // 简单的Cron表达式解析显示
      const cron = row.cron_expression;
      if (cron === "0 */6 * * *") return "每6小时";
      if (cron === "0 0 * * *") return "每天";
      if (cron === "*/15 * * * *") return "每15分钟";
      return cron;
    },
  },
  {
    label: "上次执行",
    prop: "last_run_time",
    width: 160,
    show: true,
    render: (row) => {
      if (!row.last_run_time) return "-";
      return row.last_run_time;
    },
  },
  {
    label: "上次执行状态",
    prop: "last_run_status",
    width: 120,
    show: true,
    render: (row) => {
      if (!row.last_run_status) return "-";
      const statusMap: Record<
        string,
        { text: string; type: "success" | "warning" | "info" | "danger" | "" }
      > = {
        success: { text: "成功", type: "success" },
        failed: { text: "失败", type: "danger" },
        running: { text: "运行中", type: "info" },
      };
      const item = statusMap[row.last_run_status] || {
        text: row.last_run_status,
        type: "info" as const,
      };
      return h(
        ElTag,
        { type: item.type || "info", size: "small" },
        () => item.text
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 320,
    show: true,
    slot: "history_action",
    fixed: "right",
  },
]);

const fetchTaskList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    };

    if (filterForm.status) {
      params.status = filterForm.status;
    }

    if (filterForm.keyword?.trim()) {
      params.keyword = filterForm.keyword.trim();
    }

    const result = await getGithubTasks(params);

    if (result.code === 2000 && result.data) {
      taskList.value = result.data.tasks || [];
      pagination.total = result.data.total || 0;
    } else {
      ElMessage.error(result.message || "获取任务列表失败");
      taskList.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取任务列表失败");
    taskList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchTaskList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchTaskList();
};

// 立即执行任务
const handleExecute = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要立即执行任务【${row.task_name}】吗？`,
      "执行确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 执行任务不需要设置全局loading，因为这是异步操作
    const result = await executeGithubTask(row.id);
    if (result.code === 2000) {
      ElMessage.success("任务已提交执行，请稍后查看执行结果");
      // 延迟刷新列表，给后端一些处理时间
      setTimeout(() => {
        fetchTaskList();
      }, 1000);
    } else {
      ElMessage.error(result.message || "执行任务失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "执行任务失败");
    }
  }
};

// 删除任务
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务【${row.task_name}】吗？此操作不可恢复`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    try {
      const result = await deleteGithubTask(row.id);
      if (result.code === 2000) {
        ElMessage.success("任务已删除");
        fetchTaskList();
      } else {
        ElMessage.error(result.message || "删除任务失败");
      }
    } catch (error: any) {
      ElMessage.error(error?.message || "删除任务失败");
    }
  } catch (error: any) {
    // 用户取消删除，不需要处理
    if (error !== "cancel") {
      ElMessage.error(error?.message || "删除任务失败");
    }
  }
};

// 编辑任务
const handleEdit = (row: any) => {
  currentEditTask.value = { ...row };
  showEditTaskDialog.value = true;
};

// 查看任务详情
const handleViewDetail = (row: any) => {
  currentDetailTaskId.value = row.id;
  showDetailDialog.value = true;
};

// 导出报告
const handleExportReport = (taskId: number) => {
  ElMessage.info("导出报告功能待实现");
  // TODO: 实现导出报告功能
};

// 搜索
const handleSearch = (formData: Record<string, any>) => {
  Object.assign(filterForm, formData);
  pagination.currentPage = 1;
  fetchTaskList();
};

// 重置筛选
const handleReset = () => {
  filterForm.status = "";
  filterForm.keyword = "";
  formRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchTaskList();
};

onMounted(() => {
  fetchTaskList();
});

defineExpose({
  fetchTaskList,
});
// 新增任务
const handleAddTask = () => {
  showAddTaskDialog.value = true;
};

// 任务创建成功回调
const handleTaskCreated = () => {
  fetchTaskList();
};

// 任务更新成功回调
const handleTaskUpdated = () => {
  currentEditTask.value = null;
  fetchTaskList();
};
</script>

<template>
  <div class="github-task-management">
    <el-card style="margin-bottom: 20px">
      <DynamicForm
        :form-config="formConfig"
        :model-value="filterForm"
        type="search"
        ref="formRef"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>
    <el-card>
      <DynamicTable
        :pagination="pagination"
        :columns="historyColumns"
        :data="taskList"
        :loading="loading"
        :showToolbar="true"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleAddTask">
            新增任务
          </el-button>
        </template>
        <template #history_action="{ row }">
          <div class="action-buttons">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
              title="查看详情"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              size="small"
              :disabled="row.task_status === 'running'"
              @click="handleExecute(row)"
              title="立即执行"
            >
              执行
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleEdit(row)"
              title="编辑"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              title="删除"
            >
              删除
            </el-button>
          </div>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 新增任务对话框 -->
    <AddTaskDialog v-model="showAddTaskDialog" @success="handleTaskCreated" />

    <!-- 编辑任务对话框 -->
    <AddTaskDialog
      v-model="showEditTaskDialog"
      :task-data="currentEditTask"
      @success="handleTaskUpdated"
    />

    <!-- 任务详情对话框 -->
    <TaskDetailDialog
      v-model="showDetailDialog"
      :task-id="currentDetailTaskId"
      @export="handleExportReport"
    />
  </div>
</template>

<style scoped lang="scss">
.github-task-management {
  padding: 20px;

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
  }
}
</style>
